﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using DotNetNuke.Entities.Tabs;
using iFinity.DNN.Modules.UrlMaster;
using iFinity.DNN.Modules.DNNSocialUrlProvider.Entities;
namespace iFinity.DNN.Modules.DNNSocialUrlProvider 
{
    [Serializable]
    public class ModuleFriendlyUrlProvider : iFinity.DNN.Modules.UrlMaster.ModuleFriendlyUrlProvider
    {
        #region private members
        FriendlyUrlOptions _options = null; //local copy of the Friendly Url Options, which control things like the inclusion of hyphens instead of spaces, etc.
        //the following set of members are specific to this module, and are used to control how the module provider works.
        //these are read from the web.config file, and appear as attributes in the Module Provider declaration
        protected int _groupPageTabId = -1; //- used to specify if the  module is on a page where the page path should not be included in the url.
        protected bool _hideGroupPagePath = true; //- if true, hides the group page path in the Url
        protected string _urlPath;//- specifies the url path to use for a DNNSocialUrlProvider Url
        
        #endregion

        #region overridden methods and properties
        /// <summary>
        /// Constructor for the DNNSocialUrlProvider Url Provider.  This is called by the Url Master module when loading the Provider
        /// </summary>
        /// <param name="name">Name is supplied from the web.config file, and specifies the unique name of the provider</param>
        /// <param name="attributes">Attributes are the xml attributes from the file</param>
        /// <param name="portalId">The portalId is supplied for the calling portal.  Each instance of the provider is portal specific.</param>
        public ModuleFriendlyUrlProvider(string name, NameValueCollection attributes, int portalId)
            : base(name, attributes, portalId)
        {
            //look for an attribute specifying which tab the module
            //will not use a page path for with group urls.  There can only be one
            //groups tab specified per portal 
            string groupPageTabIdRaw = attributes["groupPageTabId"];
            int temp = -1; bool tempBool = false;
            if (string.IsNullOrEmpty(groupPageTabIdRaw) == false && int.TryParse(groupPageTabIdRaw, out temp))
                _groupPageTabId = temp;

            string hideGroupPagePathRaw = attributes["hideGroupPagePath"];
            if (string.IsNullOrEmpty(hideGroupPagePathRaw) == false && bool.TryParse(hideGroupPagePathRaw, out tempBool))
                _hideGroupPagePath = tempBool;

            _urlPath = attributes["urlPath"];
        }
        /// <summary>
        /// The Change Friendly Url method is called for every Url generated when a page is generated by DotNetNuke.  This call sits 'underneath' the 'NavigateUrl' call in DotNetNuke.
        /// Whenever your module calls NavigateUrl, this method will be also called.  In here, the module developer should modify the friendlyUrlPath to the final state required.
        /// However, because this call is used for all Urls on the page, not just those generated by the target module, some type of high-level filter should be used to make sure only
        /// the module Urls are modified.
        /// 
        /// </summary>
        /// <param name="tab">Current Tab</param>
        /// <param name="friendlyUrlPath">Current Friendly Url Path after going through the Friendly Url Generation process of the Url Master module.</param>
        /// <param name="options">The options currently applying to Urls in this portal (space replacement, max length, etc)</param>
        /// <param name="cultureCode">The culture code being used for this Url (if supplied, may be empty)</param>
        /// <param name="endingPageName">The page name the Url has been called with. Normally default.aspx, but may be different for some modules.</param>
        /// <param name="useDnnPagePath">Out parameter to be set by the module.  If true, the path of the DNN page will be in the Url (ie /pagename).  If false, this part of the Url will be removed. </param>
        /// <param name="messages">List of debug messages.  Add any debug information to this collection to help debug your provider.  This can be seen in the repsonse headers, and also in the 'test Url Rewrite' page in the Url Master module.</param>
        /// <returns></returns>
        public override string ChangeFriendlyUrl(DotNetNuke.Entities.Tabs.TabInfo tab, string friendlyUrlPath, iFinity.DNN.Modules.UrlMaster.FriendlyUrlOptions options, string cultureCode, ref string endingPageName, out bool useDnnPagePath, ref List<string> messages)
        {
            _options = options;//keep local copy of options
            //set default values for out parameters
            useDnnPagePath = true;
            if (messages == null) messages = new List<string>();
            //check if we want to try and modify this Url
            //first check to see if this Url is an 'edit' Url - something that loads a module-specific page.
            //we don't want to mess with these, because they're always permissions based Urls and thus
            //no need to be friendly
            if (string.IsNullOrEmpty(friendlyUrlPath) == false && Regex.IsMatch(friendlyUrlPath, @"(^|/)(mid|moduleId)/\d+/?", RegexOptions.IgnoreCase) == false)
            {
                Hashtable friendlyUrlIndex = null; //the friendly url index is the lookup we use
                //try and match incoming friendly url path to what we would expect from the module
                Regex groupUrlRegex = new Regex(@"(?<l>/)?groupid/(?<groupid>\d+)", RegexOptions.IgnoreCase);
                Match groupUrlMatch = groupUrlRegex.Match(friendlyUrlPath);
                if (groupUrlMatch.Success)
                {

                    //this is a group Url we want to try and modify
                    string rawId = groupUrlMatch.Groups["groupid"].Value;
                    int groupId = 0;
                    if (int.TryParse(rawId, out groupId))
                    {
                        //we have obtained the groupId out of the Url
                        //get the friendlyUrlIndex (it comes from the database via the cache)
                        friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(tab.PortalID, this, options);
                        if (friendlyUrlIndex != null)
                        {
                            //item urls are indexed with i + itemId ("i5") - this is so we could mix and match entities if necessary
                            string furlkey = FriendlyUrlInfo.MakeKey("group", groupId);  //create the lookup key for the friendly url index
                            string path = null;
                            //check for a child pages / group ID in the index first
                            if (_groupPageTabId > -1 && tab.ParentId == _groupPageTabId)
                            {
                                string cpFurlKey = "t" + tab.TabID.ToString() + furlkey;
                                path = (string)friendlyUrlIndex[cpFurlKey];//check if in the index for a child page
                            }
                            if (path == null) //now check for a match in the index 
                                path = (string)friendlyUrlIndex[furlkey];//check if in the index
                            if (path == null)
                            {
                                //don't normally expect to have a no-match with a friendly url path when an itemId was in the Url.
                                //could be a new item that has been created and isn't in the index
                                //do a direct call and find out if it's there
                                path = UrlController.CheckForMissingItemId(groupId, "group", tab.PortalID, this, options, ref messages);
                            }
                            if (path != null) //got a valid path
                            {
                                //url found in the index for this entry.  So replace the matched part of the path with the friendly url
                                if (groupUrlMatch.Groups["l"].Success) //if the path had a leading /, then make sure to add that onto the replacement
                                    path = base.EnsureLeadingChar("/", path);

                                /* finish it all off */
                                messages.Add("Group Friendly Url Replacing : " + friendlyUrlPath + " in Path : " + path);

                                //this is the point where the Url is modified!
                                //replace the path in the path - which leaves any other parts of a path intact.
                                friendlyUrlPath = groupUrlRegex.Replace(friendlyUrlPath, path);//replace the part in the friendly Url path with it's replacement.
                                
                                //check if this tab is the one specified to not use a path
                                if ((_groupPageTabId == tab.TabID || _groupPageTabId == tab.ParentId ) && _hideGroupPagePath)
                                    useDnnPagePath = false;//make this Url relative from the site root

                                //set back to default.aspx so that Url Master removes it - just in case it wasn't standard
                                endingPageName = DotNetNuke.Common.Globals.glbDefaultPage;
                            }
                        }
                    }
                }
            }
            return friendlyUrlPath;
        }
        /// <summary>
        /// This method is used by the Url Master Url Rewriting process.  The purpose of this method is to take the supplied array of Url parameters, and transform them into a module-specific querystring for the underlying re-written Url.
        /// </summary>
        /// <param name="urlParms">The array of parameters found after the DNN page path has been identified.  No key/valeu pairs are identified, the parameters are converted from the /key/value/key2/value2 format into [key,value,key2,value2] format.</param>
        /// <param name="tabId">TabId of identified DNN page. </param>
        /// <param name="portalId">PortalId of identified DNN portal.</param>
        /// <param name="options">The current Friendly Url options being used by the module.</param>
        /// <param name="cultureCode">Identified language/culture code, if supplied.</param>
        /// <param name="portalAlias">Identified portalAlias object for the request.</param>
        /// <param name="messages">List of debug messages.  Add to this list to help debug your module.  Can be viewed in the reponse headers of the request, or in the 'Test Url Rewriting' section of the Url Master module.</param>
        /// <param name="status">Out parameter, returns the Http status of the request.  May be 200,301,302, or 404.  For normal rewriting, return a 200 value.</param>
        /// <param name="location">If a 301 or 302 is returned in the status parameter, then this must contain a valid redirect location.  This should be a fully-qualified Url.</param>
        /// <returns>The querystring to be used for rewriting the Url. NOTE: doesn't need to include the tabid if the tabid parameter is > -1</returns>
        public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, iFinity.DNN.Modules.UrlMaster.FriendlyUrlOptions options, string cultureCode, DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, ref List<string> messages, out int status, out string location)
        {
            //store local options variable
            _options = options;
            //initialise results and output variables
            string result = ""; status = 200; //OK 
            location = null; //no redirect location
            if (messages == null) messages = new List<string>();

            Hashtable queryStringIndex = null;
            string path = string.Join("/", urlParms);
            bool found = false;
            bool siteRootMatch = false;
            if (string.IsNullOrEmpty(path) == false && Regex.IsMatch(path, @"(^|/)(mid|moduleId)/\d+/?", RegexOptions.IgnoreCase) == false)
            {
                //look for match on pattern for date and title - the pattern used by this provider
                if (urlParms.Length > 0)
                {
                    //tabid == -1 when no dnn page path is in the Url.  This means the Url Master module can't determine the DNN page based on the Url.
                    //In this case, it is up to this provider to identify the correct tabId that matches the Url.  Failure to do so will result in the incorrect tab being loaded when the page is rendered. 
                    if (tabId == -1)
                    {
                        siteRootMatch = true;
                    }
                    queryStringIndex = UrlController.GetQueryStringIndex(portalId, this, options, false);
                    List<string> keepParms = new List<string>();
                    //iterate backwards through the collection of params
                    string lookupPath = path;
                    if (string.IsNullOrEmpty(_urlPath) == false && lookupPath.StartsWith(_urlPath) && _urlPath.Length >=0)
                        lookupPath = lookupPath.Substring(_urlPath.Length);

                    for (int i = urlParms.GetUpperBound(0); i >= 0; i--)
                    {
                        //check for existence of this value in the querystring index
                        string urlParm = urlParms[i];
                        string qsKey = lookupPath.ToLower();
                        string qs = (string)queryStringIndex[qsKey];
                        if (qs != null)
                        {
                            //found a querystring match
                            found = true;
                            messages.Add("Item Matched in Friendly Url Provider.  Url : " + lookupPath + " Path : " + path);
                            result += qs;
                            break;
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(urlParm) == false)
                            {
                                //not found - remove last url parm from lookup path
                                int pos = lookupPath.Length - (urlParm.Length + 1);
                                if (pos >= 0)
                                    lookupPath = lookupPath.Remove(pos);
                                else
                                    lookupPath = "";
                                keepParms.Add(urlParm);
                            }
                        }
                    }
                    if (found)
                    {
                        //put on any remainder of the path that wasn't to do with the friendly Url
                        string remainder = base.CreateQueryStringFromParameters(keepParms.ToArray(), -1);
                        //put it all together for the final rewrite string
                        result += remainder;
                    }
                }
            }
            return result;

        }

        /// <summary>
        /// Determines when to do a redirect.  This is separate to the rewriting process.  The module developer can create any type of Url redirect here, because the entire Url of the original request is passed in.
        /// </summary>
        /// <param name="tabId">Identified TabId, if known.  -1 if no valid tabid identified.</param>
        /// <param name="portalid">Identified portalId.</param>
        /// <param name="httpAlias">Identified httpAlias of the request.</param>
        /// <param name="requestUri">The original requested Url</param>
        /// <param name="queryStringCol">The querystring collection of the original request</param>
        /// <param name="options">The friendly url options that currently apply.</param>
        /// <param name="redirectLocation">Out parameter that shows where to redirect to.</param>
        /// <param name="messages">List of messages for debug purposes.  Add to this list to help debug your module.</param>
        /// <returns>true if 301 redirect is required, false if not.  If true, the redirectLocation value must be a valid fully qualified Url.</returns>

        public override bool CheckForRedirect(int tabId, int portalid, string httpAlias, Uri requestUri, System.Collections.Specialized.NameValueCollection queryStringCol, iFinity.DNN.Modules.UrlMaster.FriendlyUrlOptions options, out string redirectLocation, ref List<string> messages)
        {
            bool doRedirect = false;
            redirectLocation = "";//set blank location
            
            //compare to known pattern of old Urls
            string path = requestUri.AbsoluteUri;
            if (string.IsNullOrEmpty(path) == false && Regex.IsMatch(path, @"(^|/)(mid|moduleId)/\d+/?", RegexOptions.IgnoreCase) == false)
            {
                //could be in old /groupId/xx format - if so, we want to redirect it
                Regex pathRegex = new Regex(@"/groupid/(?<groupid>\d+)", RegexOptions.IgnoreCase);
                Match pathMatch = pathRegex.Match(path);
                if (pathMatch.Success)
                {
                    string groupIdRaw = pathMatch.Groups["groupid"].Value;
                    int groupId;
                    if (int.TryParse(groupIdRaw, out groupId))
                    {
                        //ok, valid item Id found
                        //get the valid Url for this item
                        Hashtable friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(portalid, this, options);
                        //look up the friendly url index using the item key
                        string furlKey = FriendlyUrlInfo.MakeKey("group", groupId);
                        if (friendlyUrlIndex != null)
                        {
                            string friendlyUrl =null;
                            TabController tc = new TabController();
                            TabInfo tab = tc.GetTab(tabId, portalid, false);
                            if (tab !=null && tab.ParentId == _groupPageTabId)
                            {
                                //this is the child tab of the group tab
                                string cpFurlKey = "t" + tabId.ToString() + furlKey;
                                friendlyUrl = (string)friendlyUrlIndex[cpFurlKey];
                            }
                            if (friendlyUrl == null)
                                friendlyUrl = (string)friendlyUrlIndex[furlKey];
                            if (friendlyUrl != null)
                            {
                                //ok, we're going to replace this in the Url
                                if (_hideGroupPagePath == false)
                                {
                                    friendlyUrl = base.EnsureLeadingChar("/", friendlyUrl);
                                    string result = pathRegex.Replace(path, friendlyUrl);
                                    doRedirect = true;
                                    redirectLocation = result;
                                }
                                else
                                {
                                    DotNetNuke.Entities.Portals.PortalAliasInfo pa = DotNetNuke.Entities.Portals.PortalAliasController.GetPortalAliasInfo(httpAlias);
                                    if (pa != null)
                                    {
                                        DotNetNuke.Entities.Portals.PortalSettings ps = new DotNetNuke.Entities.Portals.PortalSettings(tabId, pa);
                                        redirectLocation = DotNetNuke.Common.Globals.NavigateURL(tabId, ps, "", "groupid=" + groupId);
                                        doRedirect = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return doRedirect;
        }

        public override string FriendlyName
        {
            get { return "iFinity DNNSocialUrlProvider Friendly Url Provider"; }
        }
        /// <summary>
        /// Returns any custom settings that are specific per-portal for this instance
        /// </summary>
        /// <remarks>
        /// This is used to write the values back out to the web.config from the Url Master UI
        /// </remarks>
        /// <returns>A Dictionary of the key/value pairs of the settings used in this provider.  Return empty dictionary if no portal specific options.</returns>
        public override Dictionary<string, string> GetProviderPortalSettings()
        {
            //returns the settings specific to this portal instance
            Dictionary<string, string> settings = new Dictionary<string, string>();
            if (_urlPath != null && _urlPath != "")
                settings.Add("urlPath", _urlPath);

            if (_groupPageTabId > 0 )
                settings.Add("groupPageTabId", _groupPageTabId.ToString());
            else
                settings.Add("groupPageTabId", "");

            settings.Add("hideGroupPagePath", _hideGroupPagePath.ToString());
                
            return settings;
        }

        public override bool AlwaysUsesDnnPagePath(int portalId)
        {
            if (_hideGroupPagePath && _groupPageTabId > 0)
            {
                return false;//if there is any url which removes the dnn page path, then return false
            }
            else
                return true;//no url which removes the dnn page path, return true every time
        }
        public override bool IsLicensed(Uri requestUri, out string messageHtml, out string debugMessage)
        {
            //If this module had a licensing requirement, it would be checked here.  If not licensed
            //return false, and return some Html to be included on any pages where the provider is used, ie:
            //messageHtml = "<div>Hey! this isn't licensed!</div>"; debugMessage = "Fake licence message";
            //return false;

            //but in this case, there's no licensing restrictions with this provider, so always return true
            //and return nothing for the messagehtml and debugmessage
            messageHtml = null; debugMessage = null;
            return true; 
        }
        /// <summary>
        /// Returns the Path of the Settings .ascx control (if supplied).  The Settings control is loaded by the Portal Urls page for the provider,
        /// and allows interaction of the settings by the end user, at a per-portal level.
        /// </summary>
        /// <remarks>
        /// Return empty or null string if no control exists.  The path should match the path specified in the DNN install manifest, and 
        /// point to an actual file.
        /// </remarks>
        public override string SettingsControlSrc
        {
            get { return "DesktopModules/iFinity.DNNSocialUrlProvider/Settings.ascx"; }
        }
        

#endregion
        #region internal methods and properties
        internal new string CleanNameForUrl(string title, FriendlyUrlOptions options)
        {
            bool replaced = false;
            //the base module Url PRovider contains a Url cleaning routine, which will remove illegal and unwanted characters from a string, using the specific friendly url options
            return base.CleanNameForUrl(title, options, out replaced);
        }
        #endregion

        internal int GroupPagePathTabId {
            get { return _groupPageTabId; }
            set { _groupPageTabId = value; }
        }
        internal bool HideGroupPagePath {
            get { return _hideGroupPagePath; }
            set { _hideGroupPagePath = value; }
        }
        internal string UrlPath {
            get { return _urlPath; }
            set { _urlPath = value; }
        }
    }
}
